package filejoiner.method;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import filejoiner.data.Entry;
import filejoiner.data.WorkPath;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Luis
 */
public class ImageShackMethod implements Method {

    private Client client = Client.create();
    private WebResource webResource = client.resource("http://www.imageshack.us/upload_api.php");

    @Override
    public String getHost() {
        return "imageshack.us";
    }

    @Override
    public Boolean upload(Entry entry, File file, WorkPath workPath) {
        FormDataMultiPart multiPart = new FormDataMultiPart();
        multiPart.bodyPart(new FileDataBodyPart("fileupload", file));
        ClientResponse clientResponse = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, multiPart);
        String entity = clientResponse.getEntity(String.class);
        int start = entity.indexOf("<image_link>");
        int end = entity.indexOf("</image_link>");
        try {
            entry.setUrl(new URL(entity.substring(start + "<image_link>".length(), end)));
        } catch (MalformedURLException ex) {
            Logger.getLogger(ImageShackMethod.class.getName()).log(Level.SEVERE, null, ex);
        }
        return clientResponse.getStatus() == ClientResponse.Status.OK.getStatusCode() ? true : false;
    }

    @Override
    public Boolean Download(Entry entry, WorkPath workPath) {
        InputStream inputStream = null;
        try {
            inputStream = entry.getUrl().openConnection().getInputStream();
            File file = new File(workPath.getTempPath() + entry.getName());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] array = new byte[1000];
            int leido = inputStream.read(array);
            while (leido > 0) {
                fileOutputStream.write(array, 0, leido);
                leido = inputStream.read(array);
            }
        } catch (IOException ex) {
            Logger.getLogger(ImageShackMethod.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(ImageShackMethod.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return true;
    }
}
